package org.zbclan.bf2.rcon.home.server;

import java.util.Hashtable;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import net.customware.gwt.dispatch.server.ActionHandler;
import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.ActionException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zbclan.bf2.rcon.common.server.ServerModel;
import org.zbclan.bf2.rcon.common.shared.GamePlayObject;
import org.zbclan.bf2.rcon.home.shared.GetLevelNameListCommand;
import org.zbclan.bf2.rcon.home.shared.GetLevelNameListResult;

import com.google.inject.Inject;
import com.google.inject.Provider;

public class GetLevelNameListHandler implements
		ActionHandler<GetLevelNameListCommand, GetLevelNameListResult> {

	private static final Logger logger = LoggerFactory
			.getLogger(GetLevelNameListHandler.class);

	// private final Log logger;
	private final Provider<ServletContext> servletContext;
	private final Provider<HttpServletRequest> servletRequest;
	private ServerModel serverModel;

	@Inject
	public GetLevelNameListHandler(
			final Provider<ServletContext> servletContext,
			final Provider<HttpServletRequest> servletRequest,
			ServerModel serverModel) {
		// this.logger = logger;
		this.servletContext = servletContext;
		this.servletRequest = servletRequest;
		this.serverModel = serverModel;
	}

	public GetLevelNameListResult execute(final GetLevelNameListCommand cmd,
			final ExecutionContext context) throws ActionException {

		try {
			// File[] levelDirArray = levelsDir.listFiles(new FileFilter() {
			//
			// public boolean accept(File pathname) {
			// return pathname.isDirectory();
			// }
			// });
			// ArrayList<String> names = new ArrayList<String>(
			// levelDirArray.length);
			// for (File levelDir : levelDirArray) {
			// names.add(levelDir.getName());
			// }

			Hashtable<String, Hashtable<String, GamePlayObject>> levels = serverModel
					.getLevels();
			Set<String> names = levels.keySet();

			GetLevelNameListResult result = new GetLevelNameListResult();
			// result.setNames(new String[] { "a", "b" });
			result.setNames(names.toArray(new String[names.size()]));

			return result;
		} catch (Exception cause) {
			logger.error("Unable to send message", cause);
			throw new ActionException(cause);
		}

	}

	public void rollback(final GetLevelNameListCommand action,
			final GetLevelNameListResult result, final ExecutionContext context)
			throws ActionException {
		// Nothing to do here
	}

	public Class<GetLevelNameListCommand> getActionType() {
		return GetLevelNameListCommand.class;
	}
}